#include "helper.h"
#include "commdef.h"

time_t Time()
{
#define UNIXTIME_BASE	((_int64)0x019db1ded53e8000)

	SYSTEMTIME st;
	__int64	ft;
	
	::GetLocalTime( &st );
	::SystemTimeToFileTime( &st, (FILETIME*)&ft );
	return (time_t)((ft-UNIXTIME_BASE)/10000000);
}

char* Ctime( SYSTEMTIME* st )
{
	static char buf[] = "Mon Jan 01 00:00:00 2999";
	static char* wday = "SunMonTueWedThuFriSat";
	static char* mon = "JanFebMarAprMayJunJulAugSepOctNovDec";
	SYSTEMTIME _st;
	if( st == NULL )
	{
		st = &_st;
		::GetLocalTime( st );
	}
	wsprintf( buf, "%.3s %.3s %02d %02d:%02d %04d", &wday[st->wDayOfWeek*3], &mon[(st->wMonth - 1)*3],
		st->wDay, st->wHour, st->wMinute, st->wSecond, st->wYear );
	return buf;
}

char* separate_token( char* buf, char separetor, char** handle )
{
	char* tmHandle;

	if( handle == NULL )
		handle = &tmHandle;

	if( buf ) *handle = buf;

	if( *handle == NULL || **handle == 0 )
		return	NULL;

	while( **handle == separetor )
		(*handle)++;
	buf = *handle;

	if (**handle == 0)
		return	NULL;

	while (**handle && **handle != separetor)
		(*handle)++;

	if (**handle == separetor)
		*(*handle)++ = 0;

	return	buf;
}

bool GetLastErrorMsg( char *msg, HWND hWnd )
{
	char buf[MAX_BUF] = { 0 };
	wsprintf( buf, "%s error = %x", msg ? msg : "", GetLastError() );
	return MessageBox( hWnd, buf, MSG_STR, MB_OK ) ? true : false;
}

bool GetSockErrorMsg( char *msg, HWND hWnd )
{
	char buf[MAX_BUF] = { 0 };
	wsprintf( buf, "%s error = %d", msg ? msg : "", WSAGetLastError() );
	return MessageBox( hWnd, buf, MSG_STR, MB_OK ) ? true : false;
}

ULONG ResolveAddr( const char* host )
{
	if( host == NULL ) return 0;

	ULONG addr = ::inet_addr( host );
	if( addr == 0xffffffff )
	{
		hostent* ent = ::gethostbyname( host );
		addr = ent ? *(ULONG*)ent->h_addr_list[0] : 0;
	}
	return addr;
}